package com.jl.juc.completablefuture;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * 简单使用案例
 */
public class CompletableFutureDemo1 {

    /**
     * runAsync 使用默认线程池
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void testRunAsync1() throws ExecutionException, InterruptedException {

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {

            //ForkJoinPool.commonPool-worker-25
            System.out.println(Thread.currentThread().getName());

            //暂停
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //暂停
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //没有返回值
        Void aVoid = completableFuture.get();
        System.out.println(aVoid);

    }


    /**
     * runAsync 使用自定义线程池
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void testRunAsync2() throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {

            //pool-1-thread-1
            System.out.println(Thread.currentThread().getName());

            //暂停
            try {
                TimeUnit.SECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executorService);

        //没有返回值
        Void aVoid = completableFuture.get();
        System.out.println(aVoid);

    }


    /**
     * runAsync 使用自定义线程池
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void testSupplyAsync() throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {

            //pool-1-thread-1
            System.out.println(Thread.currentThread().getName());

            //暂停
            try {
                TimeUnit.SECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 3;
        }, executorService);

        //没有返回值
        Integer integer = completableFuture.get();
        System.out.println(integer);

    }
}
